/* Copyright 2010 by Matt Van Der Westhuizen */

package org.chaoticengine.ast.model;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

/**
 *
 * @author Matt Van Der Westhuizen <mattpwest@gmail.com>
 */
@Root
public class LocationFactory {
    protected static LocationFactory instance = null;
    protected HashMap<String, Location> terrains = null;

    private LocationFactory() {
        terrains = new HashMap<String, Location>();
    }

    public static LocationFactory getInstance() {
        if (instance == null) {
            instance = LocationFactory.load();
        }

        return(instance);
    }

    private static LocationFactory load() {
        String filename = "data/Locations.xml";
        Serializer srl = new Persister();
        File source = new File(filename);
        LocationFactory result = null;
        try {
            result = srl.read(LocationFactory.class, source);
        } catch (Exception ex) {
            result = new LocationFactory();
            System.out.println("Warning: Failed to load Locations for LocationFactory from file '" + filename + "'.");
            ex.printStackTrace();
        }

        return(result);
    }

    @ElementMap(entry="location", key="name", value="location", inline=true, valueType=Location.class)
    public HashMap<String, Location> getLocations() {
        return(terrains);
    }

    @ElementMap(entry="location", key="name", value="location", inline=true, valueType=Location.class)
    public void setLocations(HashMap<String, Location> ters) {
        this.terrains = ters;

        // Assign names to the Location templates and uppercase the keys for
        // more reliable lookups.
        HashMap<String, Location> newTerrains = new HashMap<String, Location>();
        Iterator<String> keyIt = terrains.keySet().iterator();
        while (keyIt.hasNext()) {
            String key = keyIt.next();
            Location loc = terrains.get(key);
            loc.setName(key);
            newTerrains.put(key.toUpperCase(), loc);
        }

        terrains.clear();
        terrains = newTerrains;
    }

    public Location getLocation(String name) {
        Location loc = terrains.get(name.toUpperCase());
        if (loc != null) {
            return(loc.copy());
        } else {
            return(null);
        }
    }
}
